<template>
  <div class="merchant-detail">
    <div class="merchant-header">
      <el-button @click="$router.go(-1)" text>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      
      <div class="merchant-info" v-if="merchant">
        <div class="merchant-basic">
          <el-image
            :src="merchant.imageUrl || '/default-merchant.jpg'"
            class="merchant-image"
            fit="cover"
          >
            <template #error>
              <div class="image-placeholder">
                <el-icon><Shop /></el-icon>
              </div>
            </template>
          </el-image>
          
          <div class="merchant-details">
            <h2>{{ merchant.name }}</h2>
            <p class="description">{{ merchant.description }}</p>
            
            <div class="merchant-stats">
              <div class="stat-item">
                <el-rate
                  v-model="merchant.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </div>
              <div class="stat-item">
                <span class="label">配送时间：</span>
                <span>{{ merchant.deliveryTime }}分钟</span>
              </div>
              <div class="stat-item">
                <span class="label">配送费：</span>
                <span>¥{{ merchant.deliveryFee }}</span>
              </div>
              <div class="stat-item">
                <span class="label">状态：</span>
                <el-tag :type="getStatusType(merchant.status)">
                  {{ getStatusText(merchant.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="menu-section" v-if="merchant">
      <div class="menu-header">
        <h3>菜单</h3>
        <div class="menu-filter">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索菜品"
            prefix-icon="Search"
            clearable
            style="width: 200px"
          />
        </div>
      </div>
      
      <el-row :gutter="20">
        <el-col
          v-for="item in filteredMenuItems"
          :key="item.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="menu-item-card" shadow="hover">
            <div class="menu-item-image">
              <el-image
                :src="item.imageUrl || '/default-food.jpg'"
                fit="cover"
                class="image"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Food /></el-icon>
                  </div>
                </template>
              </el-image>
              
              <div class="item-status" v-if="!item.available">
                <el-tag type="danger">已售罄</el-tag>
              </div>
            </div>
            
            <div class="menu-item-info">
              <h4 class="item-name">{{ item.name }}</h4>
              <p class="item-description">{{ item.description }}</p>
              <p class="shop-name">{{ merchant.name }}</p>
              
              <div class="item-meta">
                <div class="price">¥{{ item.price }}</div>
                <div class="actions">
                  <el-button
                    type="primary"
                    size="small"
                    :disabled="!item.available"
                    @click="quickOrder(item)"
                  >
                    立即下单
                  </el-button>
                  <el-button
                    type="default"
                    size="small"
                    :disabled="!item.available"
                    @click="addToCart(item)"
                  >
                    加入购物车
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <div v-if="filteredMenuItems.length === 0" class="empty-state">
        <el-empty description="暂无菜品" />
      </div>
    </div>
    
    <!-- 购物车悬浮按钮 -->
    <div class="cart-fab" @click="showCart = true">
      <el-badge :value="cartItemCount" :hidden="cartItemCount === 0">
        <el-button type="primary" circle size="large">
          <el-icon><ShoppingCart /></el-icon>
        </el-button>
      </el-badge>
    </div>
    
    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="showCart"
      title="购物车"
      direction="rtl"
      size="400px"
    >
      <div class="cart-content">
        <div v-if="cartItems.length === 0" class="empty-cart">
          <el-empty description="购物车为空" />
        </div>
        
        <div v-else class="cart-items">
          <div
            v-for="item in cartItems"
            :key="item.id"
            class="cart-item"
          >
            <div class="item-info">
              <h4>{{ item.name }}</h4>
              <p class="item-price">¥{{ item.price }}</p>
            </div>
            
            <div class="item-actions">
              <el-input-number
                v-model="item.quantity"
                :min="1"
                :max="99"
                size="small"
                @change="updateCartItem(item)"
              />
              <el-button
                type="danger"
                size="small"
                @click="removeFromCart(item.id)"
              >
                删除
              </el-button>
            </div>
          </div>
          
          <div class="cart-footer">
            <div class="total">
              总计: ¥{{ cartTotal }}
            </div>
            <el-button
              type="primary"
              size="large"
              style="width: 100%"
              @click="checkout"
            >
              去结算
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Shop, Food, ShoppingCart } from '@element-plus/icons-vue'
import { getMerchantById, getMenuItemsByMerchant } from '../../api/merchant'

const route = useRoute()
const router = useRouter()

const merchant = ref(null)
const menuItems = ref([])
const searchKeyword = ref('')
const showCart = ref(false)
const cartItems = ref([])

const filteredMenuItems = computed(() => {
  if (!searchKeyword.value) {
    return menuItems.value
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return menuItems.value.filter(item =>
    item.name.toLowerCase().includes(keyword) ||
    item.description.toLowerCase().includes(keyword)
  )
})

const cartItemCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

const cartTotal = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
})

const getStatusText = (status) => {
  const statusMap = {
    'OPEN': '营业中',
    'CLOSED': '已打烊',
    'PENDING': '审核中',
    'REJECTED': '已拒绝'
  }
  return statusMap[status] || status
}

const getStatusType = (status) => {
  const typeMap = {
    'OPEN': 'success',
    'CLOSED': 'danger',
    'PENDING': 'warning',
    'REJECTED': 'info'
  }
  return typeMap[status] || 'info'
}

const loadMerchant = async () => {
  try {
    const response = await getMerchantById(route.params.id)
    merchant.value = response.data
  } catch (error) {
    ElMessage.error('加载商家信息失败')
  }
}

const loadMenuItems = async () => {
  try {
    const response = await getMenuItemsByMerchant(route.params.id)
    menuItems.value = response.data
  } catch (error) {
    ElMessage.error('加载菜单失败')
  }
}

const addToCart = (item) => {
  const existingItem = cartItems.value.find(cartItem => cartItem.id === item.id)
  
  if (existingItem) {
    existingItem.quantity += 1
  } else {
    cartItems.value.push({
      ...item,
      quantity: 1,
      merchantId: route.params.id,
      merchantName: merchant.value?.name || ''
    })
  }
  
  ElMessage.success('已添加到购物车')
}

// 快速下单功能
const quickOrder = (item) => {
  // 清空购物车并添加当前商品
  const quickOrderItems = [{
    ...item,
    quantity: 1,
    merchantId: route.params.id,
    merchantName: merchant.value?.name || ''
  }]
  
  cartItems.value = quickOrderItems
  
  // 将快速下单数据存储到 sessionStorage
  sessionStorage.setItem('quickOrderCart', JSON.stringify(quickOrderItems))
  
  // 直接跳转到结算页面
  router.push({
    path: '/student/checkout',
    query: {
      merchantId: route.params.id,
      quickOrder: 'true'
    }
  })
}

const updateCartItem = (item) => {
  // 购物车项目数量更新逻辑
}

const removeFromCart = (itemId) => {
  const index = cartItems.value.findIndex(item => item.id === itemId)
  if (index > -1) {
    cartItems.value.splice(index, 1)
  }
}

const checkout = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }
  
  // 将购物车数据存储到 sessionStorage
  sessionStorage.setItem('cart', JSON.stringify({
    items: cartItems.value,
    merchantId: route.params.id
  }))
  
  // 跳转到结算页面
  router.push({
    path: '/student/checkout',
    query: {
      merchantId: route.params.id
    }
  })
}

onMounted(() => {
  loadMerchant()
  loadMenuItems()
})
</script>

<style scoped>
.merchant-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.merchant-header {
  margin-bottom: 30px;
}

.merchant-info {
  margin-top: 20px;
}

.merchant-basic {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.merchant-image {
  width: 200px;
  height: 150px;
  border-radius: 8px;
  flex-shrink: 0;
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f5f5;
  color: #909399;
  font-size: 48px;
}

.merchant-details {
  flex: 1;
}

.merchant-details h2 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.description {
  color: #7f8c8d;
  margin-bottom: 20px;
  line-height: 1.5;
}

.merchant-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: #7f8c8d;
  font-size: 14px;
}

.menu-section {
  margin-top: 30px;
}

.menu-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.menu-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
}

.menu-item-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.2s;
}

.menu-item-card:hover {
  transform: translateY(-2px);
}

.menu-item-image {
  position: relative;
  height: 150px;
  overflow: hidden;
  border-radius: 8px;
}

.image {
  width: 100%;
  height: 100%;
}

.item-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.menu-item-info {
  padding: 15px 0;
}

.item-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.item-description {
  margin: 0 0 8px 0;
  color: #7f8c8d;
  font-size: 14px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.shop-name {
  margin: 0 0 12px 0;
  color: #409eff;
  font-size: 12px;
  font-weight: 500;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 10px;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 90px;
}

.actions .el-button {
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 4px;
}

.price {
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.cart-fab {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 1000;
}

.cart-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-cart {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-items {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.item-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #2c3e50;
}

.item-price {
  margin: 0;
  color: #f56c6c;
  font-weight: 600;
}

.item-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-footer {
  margin-top: auto;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.total {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 15px;
  text-align: center;
}
</style>
